import React, { Suspense, Component } from "react";
import store from "@/store";
import {SpinLoading} from "antd-mobile";
import style from "./index.module.scss"

class ErrorBoundary extends Component {
  state = {
    hasError: false,
  };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error) {
    // 可以做一些错误的打印
    console.log(error);
  }

  handleRetry = () => {
    this.setState({ hasError: false });
  };

  render() {
    const { hasError } = this.state;
    const { children } = this.props;
    if (hasError) {
      return (
        <div>
          <span>出错了</span>
          <button onClick={this.handleRetry}>请重试</button>
        </div>
      );
    }
    return children;
  }
}

// 路由(组件的)懒加载：
// 1）、React.lazy()和Suspense组件配合
// 2）、边界处理的组件：ErrorBoundary。

// export const WithLazy = (loadAction) => {
//   const MyComponent = React.lazy(loadAction);
//   return (props) => (<ErrorBoundary>
//     <Suspense fallback={<div>请等待·····</div>}>
//       <MyComponent {...props}></MyComponent>
//     </Suspense>
//   </ErrorBoundary>)
// }

export const WithLazy = (loadAction) => {
  const MyComponent = React.lazy(loadAction);
  return class Com extends Component {
    state = {
      isLoading1: store.getState().isLoading1
    };

    componentDidMount() {
      store.subscribe(() => {
        this.setState({
          isLoading1: store.getState().isLoading1
        })
      })
    }
    render() {
      return (
        <>
          <ErrorBoundary>
            <Suspense fallback={<div>请等待·····</div>}>
              <MyComponent {...this.props}></MyComponent>
            </Suspense>
          </ErrorBoundary>
          <div
            className={style.loading}
            style={{ display: this.state.isLoading1 ? "block" : "none" }}
          >
            <SpinLoading color="primary" />
          </div>
        </>
      )
    }
  }
}

// export const WithLazy =WithLazy;

export const withRetry = (loadAction) => (props) => (
  <ErrorBoundary>
    {(() => {
      const Component = React.lazy(loadAction)
      return (
        <Suspense>
          <Component {...props} />
        </Suspense>
      )
    })()}
  </ErrorBoundary>
)

